package pres.man.interview.bigdata;

import java.io.File;
import java.io.FileOutputStream;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 往文件里写1亿条数据
 *
 * @author MAN
 * @date 2020-12-04-15:23
 */
public class Create {
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);

    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 50, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2000; i++) {
            int count = i;
            pool.execute(() -> {
                StringBuilder builder = new StringBuilder();
                for (int j = 0; j < 50000; j++) {
                    builder.append(getData());
                }
                output(builder.toString());
                System.out.println("写" + count + "条数据完成");
            });
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时" + (end - start) / 1000 + "秒");
        pool.shutdown();
    }

    private static String getData() {
        return ATOMIC_INTEGER.addAndGet(1) + "\n";
    }


    private static void output(String data) {
        try (FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\data.txt"), true)) {
            fileOutputStream.write(data.getBytes());
        } catch (Exception e) {

        }
    }
}
